﻿using System;
using System.Collections;
using System.Collections.Generic;

using IBatisNet.DataAccess;

using AUV5.Model;
using AUV5.DAL;
using AUV5.DAL.Interface;
using AUV5.DAL.Dao;
using System.Web;
using System.IO;
using AUV5.Common;

namespace AUV5.BLL
{
    /// <summary>
    /// 功能：     ServiceAttachment业务逻辑实现
    /// 作者：     lwl
    /// 日期：     2011/10/14
    /// 修改日期： 
    /// 修改人：
    /// 修改内容：
    /// </summary>
    public class ServiceAttachmentBLL : BaseBLL
    {
        private static ServiceAttachmentBLL instance = null;
        private static object syncRoot = new object();
        private IDaoManager daoManager = ServiceConfig.Instance.DaoManager;
        private IServiceAttachmentDao dao = null;

        private ServiceAttachmentBLL()
        {
            dao = ServiceAttachmentSqlMapDao.Instance;
        }

        public static ServiceAttachmentBLL Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                        {
                            instance = new ServiceAttachmentBLL();
                        }
                    }
                }
                return instance;
            }
        }

        /// <summary>
        /// 得到最大行数
        /// </summary>
        /// <returns></returns>
        public int GetMaxCounts()
        {
            try
            {
                //daoManager.BeginTransaction();

                int count = dao.GetMaxCounts();

                //daoManager.CommitTransaction();

                return count;
            }
            catch
            {
                //daoManager.RollBackTransaction();
                throw;
            }
        }

        /// <summary>
        /// 得到列表
        /// </summary>
        /// <returns></returns>
        public System.Collections.Generic.IList<ServiceAttachment> GetList()
        {
            try
            {
                //daoManager.BeginTransaction();

                System.Collections.Generic.IList<ServiceAttachment> list = dao.GetList();

                //daoManager.CommitTransaction();

                return list;
            }
            catch
            {
                //daoManager.RollBackTransaction();
                throw;
            }
        }

        /// <summary>
        /// 通过信息ID得到附件列表
        /// </summary>
        /// <param name="TopCounts"></param>
        /// <returns></returns>
        public System.Collections.Generic.IList<ServiceAttachment> GetListByServiceID(object topcount, string serviceID)
        {
            try
            {
                //daoManager.BeginTransaction();
                Hashtable ht = new Hashtable();
                ht.Add("TopCount", topcount);
                ht.Add("ServiceID", serviceID);
                ht.Add("State", Convert.ToInt16(Common.Enum.auvState.Enabled));
                ht.Add("IsDel", Convert.ToInt16(Common.Enum.auvDel.NotDel));

                //不用限制是否有Video，因为Video同样要显示截图
                System.Collections.Generic.IList<ServiceAttachment> list = dao.GetListByParameters(ht);

                //daoManager.CommitTransaction();

                return list;
            }
            catch
            {
                //daoManager.RollBackTransaction();
                throw;
            }
        }


        /// <summary>
        /// 得到明细
        /// </summary>
        /// <param name="AttachmentID"></param>
        /// <returns></returns>
        public ServiceAttachment GetDetail(System.String attachmentid)
        {
            try
            {
                ///daoManager.BeginTransaction();

                return dao.GetDetail(attachmentid);

                ///daoManager.CommitTransaction();
            }
            catch
            {
                ///daoManager.RollBackTransaction();
                throw;
            }
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="serviceattachment"></param>
        /// <returns></returns>
        public void Add(ServiceAttachment att)
        {
            try
            {
                //daoManager.BeginTransaction();
                //如果添加的是视频
                //将state设为0，等待后台审核
                if (!string.IsNullOrEmpty(att.VideoPath))
                {
                    //如果已经存在视频附件则修改视频和图片路径
                    ServiceAttachment existedatt = GetVideo(att.ServiceID);
                    if (existedatt != null)
                    {
                        existedatt.ImagePath = att.ImagePath;
                        existedatt.VideoPath = att.VideoPath;
                        existedatt.State = (int)Common.Enum.auvState.Enabled;
                        existedatt.IsDel = (int)Common.Enum.auvDel.NotDel;
                        Update(existedatt);
                    }
                    //否则直接将视频和图片信息添加到数据库中
                    else
                    {
                        //将服务信息中的HasVideo设为true
                        ServiceInfo service = ServiceInfoBLL.Instance.GetDetail(att.ServiceID);
                        service.HasVideo = true;
                        ServiceInfoSqlMapDao.Instance.Update(service);
                        att.AttachmentID = Guid.NewGuid().ToString();
                        dao.Add(att);
                    }
                }
                //如果添加的是图片 
                else
                {
                    att.AttachmentID = Guid.NewGuid().ToString();
                    dao.Add(att);
                }

                //daoManager.CommitTransaction();
            }
            catch
            {
                //daoManager.RollBackTransaction();
                throw;
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="serviceattachment"></param>
        /// <returns></returns>
        public int Update(ServiceAttachment serviceattachment)
        {
            try
            {
                ///daoManager.BeginTransaction();

                return dao.Update(serviceattachment);

                ///daoManager.CommitTransaction();
            }
            catch
            {
                ///daoManager.RollBackTransaction();
                throw;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="AttachmentID"></param>
        /// <returns></returns>
        public int Delete(System.String attachmentid)
        {
            try
            {
                ///daoManager.BeginTransaction();

                return dao.Delete(attachmentid);

                ///daoManager.CommitTransaction();
            }
            catch
            {
                ///daoManager.RollBackTransaction();
                throw;
            }
        }
        /// <summary>
        /// 删除
        /// 如果删除的是视频，则要将服务信息中的HasVideo设为False
        /// </summary>
        /// <param name="serviceattachment"></param>
        /// <returns></returns>
        public int Delete(ServiceAttachment serviceattachment)
        {
            try
            {
                daoManager.BeginTransaction();
                ServiceInfo service = ServiceInfoBLL.Instance.GetDetail(serviceattachment.ServiceID);
                service.HasVideo = false;
                ServiceInfoSqlMapDao.Instance.Update(service);


                int ret = 0;
                ret = dao.Delete(serviceattachment);

                daoManager.CommitTransaction();
                return ret;
            }
            catch
            {

                daoManager.RollBackTransaction();
                throw;
            }
        }

        /// <summary>
        /// 批量删除附件
        /// </summary>
        /// <param name="ht"></param>
        public void DeleteList(Hashtable ht)
        {
            try
            {
                dao.Delete(ht);
            }
            catch
            {

                throw;
            }
        }

        /// <summary>
        /// 判断附件中是否有视频
        /// 包括已审核和未通过审核的
        /// </summary>
        /// <returns></returns>
        public ServiceAttachment GetVideo(string serviceID)
        {
            Hashtable ht = new Hashtable();
            ht.Add("ServiceID", serviceID);
            ht.Add("IsVideo", true);
            IList<ServiceAttachment> list = dao.GetListByParameters(ht);
            if (list.Count > 0)
            {
                return list[0];
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 根据ServiceID获取最新添加的图片
        /// </summary>
        /// <param name="serviceID"></param>
        /// <returns></returns>
        public string GetLastImage(string serviceID)
        {
            try
            {
                IList<Model.ServiceAttachment> list = BLL.ServiceAttachmentBLL.Instance.GetListByServiceID(1, serviceID);
                if (list.Count > 0)
                {
                    string path = list[0].ImagePath;
                    if (string.IsNullOrEmpty(path))
                    {
                        return Common.CommonDefine.IAMGE_DEFAULT;
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(list[0].VideoPath))
                        {
                            return GetImageThumb(path);
                        }
                        else
                        {
                            return path;
                        }
                    }
                }
                else
                {
                    return "";
                }
            }
            catch
            {

                throw;
            }
        }

        /// <summary>
        /// 添加视频信息
        /// </summary>
        /// <param name="serviceID"></param>
        /// <param name="videopath"></param>
        public void AddVideo(string serviceID, string videopath)
        {
            try
            {
                Model.ServiceAttachment att = new Model.ServiceAttachment();
                string sourceFile = HttpContext.Current.Server.MapPath(videopath);
                att.ServiceID = serviceID;
                DateTime addate = ServiceInfoBLL.Instance.GetDetail(serviceID).CreateDate;
                string destpath = "/UploadFile/Video/" + addate.Year.ToString() + "/" + addate.Month.ToString() + "/" + addate.Day.ToString() + "/";
                if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(destpath)))
                {
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(destpath));
                }
                string uniquename = FileHelper.GetUniqueFileName();

                //转换MP4格式
                FormatConverter mp4converter = new FormatConverter();
                string mp4 = mp4converter.Convert(sourceFile, destpath, uniquename, FormatConverter.VideoType.MP4, false, false);

                //转换Flv格式
                FormatConverter flvconverter = new FormatConverter();
                string flv= flvconverter.Convert(sourceFile, destpath,uniquename,FormatConverter.VideoType.FLV,true,true);
                
                if (flv == "")
                {
                    if (flvconverter.DestVideo != "")
                    {
                        att.VideoPath = flvconverter.DestVideo;
                        att.VideoLength = flvconverter.VideoLength;
                    }
                    if (flvconverter.DestImage != "")
                    {
                        att.ImagePath = flvconverter.DestImage;
                    }
                    att.State = (int)Common.Enum.auvState.Enabled;
                    att.IsDel = (int)Common.Enum.auvDel.NotDel;
                    att.CreateDate = DateTime.Now;
                    att.UpdateDate = DateTime.Now;
                    att.BeginDate = DateTime.Now;
                    att.EndDate = DateTime.Now;
                    BLL.ServiceAttachmentBLL.Instance.Add(att);
                }
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 获取信息服务的图片路径List
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public string GetImgPathList(string serviceID)
        {
            try
            {
                string pathlist = "";
                IList<ServiceAttachment> list = BLL.ServiceAttachmentBLL.Instance.GetListByServiceID(null, serviceID);
                for (int i = 0; i < list.Count; i++)
                {
                    if (string.IsNullOrEmpty(list[i].VideoPath))
                    {
                        if (pathlist == "")
                        {
                            pathlist = list[i].ImagePath;
                        }
                        else
                        {
                            pathlist += "," + list[i].ImagePath;
                        }
                    }
                }
                //foreach (var sa in list)
                //{
                //    if (string.IsNullOrEmpty(sa.VideoPath))
                //    {
                //        if (pathlist == "")
                //        {
                //            pathlist = sa.ImagePath;
                //        }
                //        else
                //        {
                //            pathlist += "," + sa.ImagePath;
                //        }
                //    }
                //}
                return pathlist;
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 将列表中的附件数据删除
        /// </summary>
        /// <param name="list"></param>
        public void RemoveAttachment(IList<Model.ServiceAttachment> list)
        {
            try
            {
                foreach (var item in list)
                {
                    //此处删除数据后，在添加过程中不用删除所有附件后再添加
                    BLL.ServiceAttachmentBLL.Instance.Delete(item.AttachmentID);
                    if (File.Exists(HttpContext.Current.Server.MapPath(item.ImagePath)))
                    {
                        File.Delete(HttpContext.Current.Server.MapPath(item.ImagePath));
                    }
                    if (File.Exists(HttpContext.Current.Server.MapPath(GetImageThumb(item.ImagePath))))
                    {
                        File.Delete(HttpContext.Current.Server.MapPath(GetImageThumb(item.ImagePath)));
                    }
                    if (File.Exists(HttpContext.Current.Server.MapPath(GetImagePreview(item.ImagePath))))
                    {
                        File.Delete(HttpContext.Current.Server.MapPath(GetImagePreview(item.ImagePath)));
                    }
                }
            }
            catch
            {
                throw;
            }
        }




    }
}
